<?php
/* SVN FILE: $Id: item_downloadfile.php 247 2009-10-22 15:31:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Download File item
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 247 $
* @lastrevision $Date: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/items/item_downloadfile.php $
*/

class item_downloadfile extends templateItem
{
	/**
	 * The default name of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultName = "Download a File";
	
	/**
	 * The default description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultDescription = "When the item is used, an download popup will appear. Then the item will be deleted.";
	
	// Inherited Properties
	/**
	 * Item setting to allow multiple instances within ibMarket 
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $allowMultiple = true;
	
	/**
	 * Item specific setting
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $itemSettings = array();
	
	/**
	 * Constructor to setup the item
	 *
	 * @access	public
	 * @param	ipsRegistry	$registry	IPB registry
	 * @param	array		&$item		The item information
	 */
	public function __construct(ipsRegistry $registry, array &$item)
	{
		parent::__construct($registry, $item);
		
		if($item['item_config'] || $item['item_id'] != 0)
		{
			$this->itemSettings = unserialize($item['item_config']);
		}
		else
		{
			$this->itemSettings['linked_id'] = 0;
		}
	}
	
	/**
	 * Additional settings when adding/editing the item
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminForm()
	{
		$items = array();
		$items[] = array(0,$this->lang->words['use_upload_file']);
		$_items = marketRegistry::getItemsByFiles($this->item['filename']);
		$_items = is_array($_items) ? $_items : array();
		foreach($_items as $item)
		{
			if($item['item_id'] != $this->item['item_id'] && marketRegistry::getItem($item)->itemSettings['linked_id'] == 0)
			{
				$items[] = array($item['item_id'],marketRegistry::getItem($item)->itemSettings['filename']." (".$this->lang->words['item_id'].": ".$item['item_id'].")");
			}
		}
		
		$current = "";
		if($this->item['item_id'] != 0 && $this->itemSettings['linked_id'] == 0)
		{
			$current = <<<EOF
				<li>
					<label>{$this->lang->words['current_file_info']}</label>
					<div style="float: left">
						{$this->lang->words['file_name']}: {$this->itemSettings['filename']}
						<br />
						{$this->lang->words['file_size']}: {$this->itemSettings['filesize']} B
						<br />
						{$this->lang->words['file_location']}: {$this->itemSettings['location']}
					</div>
				</li>

EOF;
		}
		
		$form['upload'] = ipsRegistry::getClass('output')->formUpload('item_upload');
		$form['linked_id'] = ipsRegistry::getClass('output')->formDropdown('item[linked_id]', $items, $this->itemSettings['linked_id']);
		return <<<EOF
				<li>
					<label>{$this->lang->words['use_another_file']}</label>
					{$form['linked_id']}
				</li>
				<li>
					<label>{$this->lang->words['what_file_to_download']}</label>
					{$form['upload']}
				</li>
{$current}

EOF;
	}
	
	/**
	 * Saving to adding/editing the item
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	array	[$input]		Relavent input relating to the item
	 * @todo
	 * @return	void
	 */
	public function adminSave(array &$item_info, array $input)
	{
		require_once( IPS_KERNEL_PATH.'classUpload.php' );
		$upload = new classUpload();
		
		$setting = array();
		if($input['linked_id'] == 0)
		{
			if($this->item['item_id'] == 0 && ($_FILES['item_upload']['name'] == "" or ! $_FILES['item_upload']['name'] or ($_FILES['item_upload']['name'] == "none")))
			{
				$this->registry->output->showError( $this->lang->words['need_to_upload'] );
			}
			
			$id = 0;
			if($this->item['item_id'] != 0)
			{
				$id = $this->item['item_id'];
			}
			else
			{
				foreach(array_keys($this->caches['market_items']) as $item_id)
				{
					if($item_id > $id)
					{
						$id = $item_id;
					}
				}
				$id++;
			}
			
			if($_FILES['item_upload']['name'] == "" or ! $_FILES['item_upload']['name'] or ($_FILES['item_upload']['name'] == "none"))
			{
				$save = $this->itemSettings;
			}
			else
			{
				if($this->itemSettings['location'] && file_exists($this->itemSettings['location']))
				{
					@unlink( $this->settings['upload_dir']."/".$this->itemSettings['location'] );
				}
				
				$upload->out_file_name = 'market-download-'.$id;
				$upload->out_file_dir = $this->settings['upload_dir'];
				$upload->upload_form_field = 'item_upload';
				$upload->check_file_ext = false;
				$upload->process();
				
				if($upload->error_no)
				{
					$this->registry->output->showError( $this->lang->words['upload_failed'] );
				}
				
				$setting['linked_id'] = 0;
				$setting['filename'] = $upload->original_file_name;
				$setting['filesize'] = $_FILES['item_upload']['size'];
				$setting['location'] = $upload->parsed_file_name;
			}
		}
		else
		{
			if($this->caches['market_items'][$input['linked_id']]['filename'] != $this->item['filename'] || marketRegistry::getItem($this->caches['market_items'][$input['linked_id']])->itemSettings['linked_id'] != 0)
			{
				$this->registry->output->showError( $this->lang->words['invalid_item_download'] );
			}
			
			if($this->itemSettings['location'] && file_exists($this->itemSettings['location']))
			{
				@unlink( $this->settings['upload_dir']."/".$this->itemSettings['location'] );
			}
			
			$setting['linked_id'] = $input['linked_id'];
			$setting['filename'] = "";
			$setting['filesize'] = "";
			$setting['location'] = "";
		}
		
		$item_info['item_config'] = serialize($setting);
	}
	
	/**
	 * When quick saving the price and stock
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	string	$type			Possible values: 'stockprice', more possibly in the future
	 * @return	void
	 */
	public function adminQuickSave(array &$item_info, $type)
	{
		return;
	}
	
	/**
	 * When removing the item from ibMarket
	 *
	 * @access	public
	 * @return	void
	 */
	public function adminRemove()
	{
		return;
	}
	
	/**
	 * Viewing the file edits if any
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminViewFileEdits()
	{
		return false;
	}
	
	/**
	 * Any admin AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function adminAjax()
	{
		return;
	}
	
	/**
	 * Check and modify the intentory item information before storing in the database
	 *
	 * @access	public
	 * @param	array	&$invItem		The new inventory item information to be stored in the database.
	 * @return	bool	true if the item is successfully created, false otherwise
	 */
	public function publicOnCreateItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When using the item
	 * Show a form and validate the form
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	string|bool				string if there is a form to be used, true if successfully used, false otherwise
	 */
	public function publicUseItem(array &$invItem)
	{
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_items' ) );
		
		if($this->itemSettings['linked_id'])
		{
			$config = marketRegistry::getItem($this->caches['market_items'][$this->itemSettings['linked_id']])->itemSettings;
		}
		else
		{
			$config = $this->itemSettings;
		}
		
		$this->deleteItems($invItem);
		
		$this->writeLog($invItem, "Download file: ".$config['filename']);
		
		header('Content-Type: unknown/unknown');
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Content-Disposition: attachment; filename="' . $config['filename'] . '"');
		header('Content-Length: ' . $config['filesize'] );
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		
		$fp = fopen($this->settings['upload_dir']."/".$config['location'],"rb");
		fpassthru($fp);
		fclose($fp);
		flush();
		
		exit();
	}
	
	/**
	 * Any AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function publicAjax(array &$invItem)
	{
		return;
	}
	
	/**
	 * When the item is being sold back
	 *
	 * @access	public
	 * @param	array	&$invItem	The inventory item information
	 * @return	bool				true if successful, false otherwise
	 */
	public function publicOnResoldItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When the item is being restocked
	 *
	 * @access	public
	 * @param	array	&$item	The inventory item information
	 * @return	void
	 */
	public function onItemRestock(array &$item)
	{
		return;
	}
}
